#include "oewalletloginwidget.h"
#include <QDebug>


#include <QPainter>
#include <QPixmap>
#include <QDir>
#include <QSettings>
#include <QPushButton>
#include <QSignalMapper>

#include <OEFlowLayout>

OEWalletLoginWidget::OEWalletLoginWidget(QWidget *parent)
    : QWidget(parent)
{
    /// attribute
    setWindowTitle(tr("wallet"));

    // wallet info
    mapFileName_.insert("wallet", "wallet");
    // cryptographic seed
    mapFileName_.insert("seedname", "seed");

    // layout
    layout_ = new OEFlowLayout();
    layout_->setMargin(0);
    layout_->setSpacing(0);
    layout_->setContentsMargins(0,0,0,0);
    setLayout(layout_);

    mapper_ = new QSignalMapper(this);



    // link
    connect(mapper_, SIGNAL(mapped(QString)),
            this, SLOT(onHandoverWorkPath(QString)));

}

void OEWalletLoginWidget::clearWallet()
{
    listInfo_.clear();

    // 清理所有窗口
    while (auto item = layout_->takeAt(0)) {
        if (item) {
            layout_->removeItem(item);
            mapper_->removeMappings(item->widget());
            item->widget()->deleteLater();
        }
    }
}

int OEWalletLoginWidget::loadWallet(const QString &_path) {
    // check path
    if (!QDir(_path).exists())
        return -87;

    // clean wallet
    clearWallet();

    // load wallet info
    QStringList list_file_path = findWallet(_path);
    for (auto& filepath : list_file_path) {
        stWalletInfo info;
        if (0 != loadWalletInfo(filepath, info)) {
            qWarning() << QString("load %1 wallet error")
                            .arg(filepath);
        }
        listInfo_.push_back(info);
    }

    const int WALLET_SIZE =
            (listInfo_.size() <= 8) ? listInfo_.size() : 8;

    // create wallet widget;
    for(int i = 0; i < WALLET_SIZE; ++i){
        if (0 != createWallet(listInfo_.at(i)))
            qWarning() << QString("create %1 wallet error!")
                            .arg(listInfo_.at(i).name);
    }

    // create more wallet button
    QPushButton* btn_more = new QPushButton();
    btn_more->setStyleSheet("QPushButton{border-image:url(:/btn/more);}");
    layout_->addWidget(btn_more);
    btn_more->setFixedSize(300,300);


    return listInfo_.count();
}

int OEWalletLoginWidget::createWallet(
        const OEWalletLoginWidget::stWalletInfo &_info) {

    if (!QDir(_info.absPath).exists())
        return -1;
    QPushButton* wallet = new QPushButton();
    wallet->setToolTip(_info.name);

    // create logo button
    if (!_info.logo.isEmpty()
        && QFile(_info.logo).exists()) {
        QString logo_hover = _info.logo_hover;
        QString logo_pressed = _info.logo_pressed;
        if (logo_hover.isEmpty()
            || logo_pressed.isEmpty()) {
            // create logo hover pressed image
            createPixmap(_info.logo, logo_hover, logo_pressed);
        }
        QString style = QString("QPushButton {border-image:url(%1);}"\
                                "QPushButton:hover{border-image:url(%2);}"\
                                "QPushButton:pressed{border-image:url(%3);}")
                                  .arg(_info.logo).arg(logo_hover)
                                  .arg(logo_pressed);

        wallet->setStyleSheet(style);
    }
    // create name button
    else {
        wallet->setText(_info.name);
    }

    wallet->setFixedSize(300,300);

    // link wallet
    mapper_->setMapping(wallet, _info.absPath);
    connect(wallet, SIGNAL(clicked()),
            mapper_, SLOT(map()));

    layout_->addWidget(wallet);
    return 0;
}

int OEWalletLoginWidget::loadWalletInfo(const QString &_rootpath,
        OEWalletLoginWidget::stWalletInfo &_wallet) {
    const QString& wallet_config = _rootpath + "/" + mapFileName_["wallet"];
    if (!QFile(wallet_config).exists()){
        return 87;
    }
    QSettings setting(wallet_config,QSettings::IniFormat);

    _wallet.absPath = _rootpath;

    _wallet.name = setting.value("INFO/name").toString();

    _wallet.ekPubKey = setting.value("INFO/ek_pub_key").toString();

    // res
    _wallet.logo = setting.value("RES/logo").toString();
    convertPathToAbs(_rootpath, _wallet.logo);

    _wallet.logo_hover = setting.value("RES/logo_hover").toString();
    convertPathToAbs(_rootpath, _wallet.logo_hover);

    _wallet.logo_pressed = setting.value("RES/logo_pressed").toString();
    convertPathToAbs(_rootpath, _wallet.logo_pressed);


    // custom
    QString seed_path = setting.value("CUSTOM/seedpath").toString();
    if (!seed_path.isEmpty()) {
        if (QDir::isRelativePath(seed_path))
            seed_path = _rootpath + "/" + seed_path;

        mapFileName_["seedpath"] = seed_path;
    }

    QString seed_name = setting.value("CUSTOM/seedname").toString();
    if (!seed_name.isEmpty()) {
        mapFileName_["seedname"] = seed_name;
    }


    return 0;
}

QStringList OEWalletLoginWidget::findWallet(const QString &_path) {
    QDir dir(_path);
    if (!dir.exists())
        return {};

    // only dir
    dir.setFilter(QDir::Filter::Dirs |
                  QDir::Filter::NoDotAndDotDot);
    QFileInfoList list_dir = dir.entryInfoList();

    QStringList list_path;
    for (auto& dir_iter : list_dir) {
        bool bflag = isWallet(dir_iter.absoluteFilePath());
        if(bflag) {
            list_path.push_back(dir_iter.absoluteFilePath());
        }
    }
    return list_path;
}

bool OEWalletLoginWidget::convertPathToAbs(
        const QString &_rootPath, QString &_outpath)
{
    if (_outpath.isEmpty() || !QDir::isAbsolutePath(_rootPath))
        return false;

    if (QDir::isRelativePath(_outpath))
        _outpath = _rootPath + "/" + _outpath;

    return true;
}

bool OEWalletLoginWidget::createPixmap(const QString &_logo, QString &_logoHover, QString &_logoPressed)
{
    QPixmap pix_logo(_logo);
    if (pix_logo.isNull())
        return false;

    /// 制作暗色背景
    QPixmap temp_dim_pix(pix_logo.width(), pix_logo.height());

    temp_dim_pix.fill((QColor(0, 0, 0, 20)));
    QPainter p(&pix_logo);

    // draw hover png
    p.drawPixmap(0, 0, temp_dim_pix);
    if (_logoHover.isEmpty()) {
        _logoHover = QFile(_logo).fileName();
        _logoHover.insert(_logoHover.length() - 4, "_hover");
        if (!pix_logo.save(_logoHover))
            return false;
    }

    // draw pressed png
    p.drawPixmap(0, 0, temp_dim_pix);
    if (_logoPressed.isEmpty()) {
        _logoPressed = QFile(_logo).fileName();
        _logoPressed.insert(_logoPressed.length() - 4, "_pressed");
        if (!pix_logo.save(_logoPressed))
            return false;
    }

    return true;
}

bool OEWalletLoginWidget::isWallet(const QString &_path) {
    const QString& filepath = _path + "/" + mapFileName_["wallet"];
    if (!QFile(filepath).exists())
        return false;
    return true;
}

bool OEWalletLoginWidget::onHandoverWorkPath(const QString &_absPath)
{
    if (!QDir(_absPath).exists()) {
        qCritical() << "invalid work path.";
        return false;
    }
#ifdef QT_DEBUG
    qDebug() << "current path :" << QDir::currentPath();
    qDebug() << "convert to path: " << _absPath;
#endif

    bool bflag = QDir::setCurrent(_absPath);

    if (bflag)
        emit sigFinshed(_absPath);

    return bflag;
}
